package setprite;

import java.util.Comparator;
import java.util.TreeSet;

public class Set05 {
    public static void main(String[] args) {
        //TreeSer带参构造使用的是比较器排序对比元素进行排序
        //让集合构造方法接受Comparator的实现类，重写compare(To1,To2)方法，重写方法时注意排序的规则按照主要条件和次要条件写
        //练习
        //自定义老师类，按照年龄进行排序，年龄一样按照姓名排序，姓名使用英文字母表示
//        TreeSet<Teacher>teachers=new TreeSet<>();
//        Teacher teacher=new Teacher("zhangsan",33);
//        Teacher teacher2=new Teacher("lisi",22);
//        Teacher teacher3=new Teacher("zhangba",44);
//        Teacher teacher4=new Teacher("wangwu",26);
//        teachers.add(teacher);
//        teachers.add(teacher2);
//        teachers.add(teacher3);
//        teachers.add(teacher4);
//        System.out.println(teachers);//报错，没有指定排序规则
        TreeSet<Teacher>teachers=new TreeSet<>((new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {//o1表示现在要存入的那个元素，o2表示已经存入到及集合中的元素
                int result = o1.getAge() - o2.getAge();//主要条件
                result=result==0 ? o1.getName().compareTo(o2.getName()):result;//次要条件
                return result;
            }
        }));
        Teacher teacher=new Teacher("zhangsan",33);
        Teacher teacher2=new Teacher("lisi",22);
        Teacher teacher3=new Teacher("zhangba",22);
        Teacher teacher4=new Teacher("wangwu",26);
        Teacher teacher5=new Teacher("dd",77);
        teachers.add(teacher);
        teachers.add(teacher2);
        teachers.add(teacher3);
        teachers.add(teacher4);
        teachers.add(teacher5);
        System.out.println(teachers);
        //默认使用自然排序，指定条件使用比较器，-1，0，1使用一样
    }
}
